<?php

namespace App\CustHub\Service;

use App\CustHub\Model\ChDevelopmentCourse;
use App\Setting\Service\SettingConfigService;
use Hyperf\Di\Annotation\Inject;
use Mine\Abstracts\AbstractService;
use function Hyperf\Collection\collect;

class ChGetConfigService extends AbstractService
{
    #[Inject]
    protected SettingConfigService $settingConfigService;

    public function getConfig()
    {
        $config = $this->settingConfigService->getConfigByGroupKey('site_config');

        return collect($config)->map(function ($item){
            return ['name'=>$item['name'],'key'=>$item['key'],'value'=>$item['value'],'sort'=>$item['sort']];
        })->sortByDesc('sort')->values()->toArray();
    }

    public function getJoinConfig()
    {
        $config = $this->settingConfigService->getConfigByGroupKey('joining_arrangement');

        // 取出 key => value 形式
        return collect($config)->pluck('value', 'key')->toArray();
    }


    public function getDevelopCourse()
    {
        // 一次性取出所有记录，只查需要字段，按时间升序
        $allRecords = ChDevelopmentCourse::select(['time', 'content'])->orderBy('time','desc')->get();

        $allResults = [];

        // 遍历所有记录
        foreach ($allRecords as $index => $record) {
            $time = $record->time;

            if ($index === 0) {
                // 最早，取前3条
                $subset = $allRecords->slice(0, 3);
            } elseif ($index === $allRecords->count() - 1) {
                // 最晚，取最后3条
                $subset = $allRecords->slice(-3);
            } else {
                // 中间，取前一条 + 当前 + 后一条
                $subset = collect([
                    $allRecords->get($index - 1),
                    $record,
                    $allRecords->get($index + 1)
                ]);
            }

            $allResults[] = [
                'time' => $time,
                'results' => $subset->toArray()
            ];
        }

        return $allResults;
    }

    public function getCompanyIntroduction()
    {
        $config = $this->settingConfigService->getConfigByGroupKey('company_introduction');

        $longitude = 118.76981297553266;
        $latitude = 31.962225181708003;

        $keys = $this->settingConfigService->getConfigByKey('tencent_api_key')['value'] ?? 'BOPBZ-4UNCP-KTWDK-VD4MB-76E5V-7WFLE';
        $keysArr = explode(',',$keys);
        $appKey = $keysArr[array_rand($keysArr)];

        // 取出 key => value 形式
        $companyConfig = collect($config)->pluck('value', 'key')->toArray();

        $companyConfig['address'] = [
            'longitude' => $longitude,
            'latitude' => $latitude,
            'key' => $appKey
        ];

        return $companyConfig;
    }

    public function getConsultingConfig()
    {
        $config = $this->settingConfigService->getConfigByGroupKey('consulting_config');

        // 取出 key => value 形式
        return collect($config)->pluck('value', 'key')->toArray();
    }
}